import React from 'react'
import cx from 'classnames'
import DefaultLoadingElement from 'lib/util/defaultLoadingElement.jsx'
import basicInfo from '../apis/basicInfo'
export default class AppDropdown extends React.Component{
  constructor(props){
    super(props);
    this.openMenu = this.openMenu.bind(this)
    this.closeMenu = this.closeMenu.bind(this)
    this.state = {
      currentApp:{
        id:props.appId,
        name:props.appName
      },
      open:false,
      list:null
    }
    this.api = basicInfo({
      urlName:'app',
      parentId:'0',
      appId:null
    })

  }
  openMenu(){
    var _this = this
    if(!this.state.list){
      this.api.fetch().done(function(data){
        _this.setState({
          list:data.result
        })
      })
    }
    this.setState({
      open:true
    })
  }
  closeMenu(e){
    var el = e.target
      , container = this.refs.root
    if(this.state.open&&!$.contains(container,el)){
      this.setState({
        open:false
      })
    }
  }
  componentWillUnmount(){
    $('body').off('click',this.closeMenu)
  }
  componentDidMount(){
    $('body').on('click',this.closeMenu)
  }
  toggle(){
    this.setState({
      open:!this.state.open
    })
  }
  render(){
    var ddMainStyle = {}
    if(!this.state.open){
      ddMainStyle.display = 'none'
    }
    return (
      <div className="apps" ref="root">
        <strong onClick={this.openMenu}>
          <span>{this.state.currentApp.name}</span>
          <i className="iconfont icon-btn-arrow">&#xe619;</i>
        </strong>
        <div className="dropdown-main" style={ddMainStyle}>
          {this.state.list?(
            <ul>
              <li><a href={BlueWare.pageUrlPrefix+'/app'}>应用列表</a></li>
              {this.state.list.map(function(app){
                return (
                  <li key={app.id}>
                    <a href={BlueWare.pageUrlPrefix+'/app/'+app.id+'/'+this.props.moduleName}>
                      {app.name}
                    </a>
                  </li>
                )
              },this)}
            </ul>
          ):<DefaultLoadingElement />}

        </div>
      </div>
    )
  }
}
AppDropdown.defaultProps = {
  moduleName:'overview'
}
